import json
import os
from src.general_function import TestSuite, TestCase, AllTest, get_all_utest_dirs, CustomJSONEncoder


def create_name_one_test(text):
    """
    функция, которая возвращает название одного testcase
    :param text: строка, содержащая название
    :return: название
    """
    name = text.split('.')[1].split()[0]
    return name


def create_time_one_test(text):
    """
    функция, которая возвращает время одного testcase
    :param text: строка содержащая время
    :return: время
    """
    time = text.split()[-2][1:]
    return time


def check_string_list(string_list):
    """
    Функция, создающая один блок тестов
    :param string_list: массив одного блока
    :return: объект класса TestSuite
    """
    if string_list[0] != "\n":
        name = string_list[0].split()[-1]
        text = string_list[-1]
        time = int(text[text.index("(") + 1:text.index(")") - 9])
        result_test = []
        for line, test in enumerate(string_list):
            if "[       OK ]" in test:
                result_test.append(TestCase(name=create_name_one_test(test),
                                            result="OK",
                                            time=int(create_time_one_test(test)),
                                            classname=name))
            elif "FAILED" in test:
                result_test.append(TestCase(name=create_name_one_test(test),
                                            result="FAILED",
                                            time=int(create_time_one_test(test)),
                                            classname=name))
        failures = len(list(filter(lambda i: i.result == "FAILED", result_test)))
        tests = len(result_test)
        return TestSuite(name=name,
                         tests=tests,
                         failures=failures,
                         disabled=0,
                         time=time,
                         errors=0,
                         testsuite=result_test)
    else:
        string_list.pop(0)
        return check_string_list(string_list)


def list_file(file):
    """
    Функция, создающая массив строк одного utest файла
    :param file: путь utest файла
    :return: массив строк, начиная с третьего элемента
    """
    with open(file, 'r') as file_name:
        string_list = [i_string for i_string in file_name]
        del string_list[:3]
        for i in string_list:
            if "Global test" in i:
                return string_list
        return []


def test_count_in_alltest(res):
    count = 0
    for i in res:
        count += i.tests
    return count


def fail_count_in_alltest(res):
    count = 0
    for i in res:
        count += i.failures
    return count


def dis_test(file_list):
    for i in file_list:
        if "DISABLED" in i:
            count = int(i.split()[2])
            return count
    return 0


def time_total(file_list):
    for i in file_list:
        if "[==========]" in i:
            return int(i.split()[-3][1:])


def check_directory(path):
    """

    :param path:
    :return:
    """
    for i_file in get_all_utest_dirs(path):
        string_list = list_file(os.path.join(i_file, "utest.log"))
        if not string_list:
            continue
        res = []
        number = 0
        start, end = -1, -1
        for line, test in enumerate(string_list):
            if "[--------" in test and "Global" not in test:
                if number == 0:
                    start = line
                    number += 1
                elif start >= 0 and number == 1:
                    end = line
                    number = 0
            elif start >= 0 and end >= 0:
                res.append(check_string_list(string_list[start:end+1]))
                start, end = -1, -1
        reports = AllTest(name=i_file.split("\\")[-2] + " " + i_file.split("\\")[-1],
                                    tests=test_count_in_alltest(res),
                                    failures=fail_count_in_alltest(res),
                                    disabled=dis_test(string_list[-10]),
                                    time=time_total(reversed(string_list)),
                                    errors=0,
                                    testsuites=res)
        with open(os.path.join(i_file, "results.json"), "w") as file:
            json.dump(reports, file, cls=CustomJSONEncoder, indent=4)



def fix_directory(path):
    if os.path.exists(path):
        check_directory(path)
    else:
        print("Directory not found")
        return False


if __name__ == '__main__':
    folder_path = r'C:\Users\anyca\Desktop\TestResults_Unpack'

    fix_directory(folder_path)

    # for i in get_all_utest_dirs(r'C:\Users\anyca\Desktop\TestResults_Unpack'):
    #     print(i)
    #     os.remove(os.path.join(i, 'result.json'))